class unionset
{
public:
    vector<int> fa;
    unionset(int n)
    {
        for (int i = 0; i < n; i++) fa.push_back(i);
    }
    int find(int n)
    {
        return fa[n] == n ? n : fa[n] = find(fa[n]);
    }
    void merge(int a, int b)
    {
        fa[find(a)] = find(b);
    }
    int num()
    {
        int ans = 0;
        for (int i = 0; i < fa.size(); i++)
        {
            if (fa[i] == i) ans += 1;
        }
        return ans;
    }
};

class Solution {
public:
    int findCircleNum(vector<vector<int>>& isConnected) {
        unionset s(isConnected.size());
        for (int i = 0; i < isConnected.size(); i++)
        {
            for (int j = 0; j < isConnected[i].size(); j++)
            {
                if (isConnected[i][j]) s.merge(i, j);
            }
        }
        return s.num();
    }
};